<template>
  <div>
    <van-cell v-for="(item,index) in suggestion"
              :key="index"
              icon="search">
      <div @click="$emit('search', item)"
           slot="title"
           v-html="textActive(item)"></div>
    </van-cell>
  </div>
</template>

<script>
import { getSearchSuggestion } from '@/api/search.js'
export default {
  data () {
    return {
      suggestion: [],
      setId: null
    }
  },
  props: {
    searchtext: {
      type: String,
      required: true
    }
  },
  watch: {
    searchtext: {
      immediate: true,
      handler () {
        clearTimeout(this.setId)
        this.setId = setTimeout(_ => {
          this.loadSuggestion()
        }, 800)
      }
    }
  },
  created () {

  },

  methods: {
    async loadSuggestion () {
      try {
        const { data: res } = await getSearchSuggestion(this.searchtext)
        this.suggestion = res.data.options
      } catch (err) {
        this.$toast('获取联想建议失败')
      }
    },
    textActive (str) {
      const reg = new RegExp(this.searchtext, 'gi')
      str = str.replace(reg, '<span style="color: red">' + this.searchtext + '</span>')
      return str
    }
  }
}
</script>

<style scoped lang='less'>
</style>
